package com.xlk.restful.dao.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.opensaml.xacml.ctx.provider.BaseObligationHandler;

import com.core.db.impl.MongoDBDAOImpl;
import com.core.util.MongoUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.xlk.restful.dao.RESTSampleDAO;
import com.xlk.restful.domain.MapBean;
import com.xlk.restful.domain.User;
/**
 * 
 * TODO </br> 
 * 类名: RESTSampleImpl </br> 
 * 日期: 2014-2-28 上午11:04:01 </br> 
 * @author 许立亢 
 * @version 1.0
 */
public class RESTSampleDAOImpl extends MongoDBDAOImpl implements RESTSampleDAO{
	
	private DBCollection rest;
	
	
	
	
	@Override
	public void deleteData(int id) {
		DBObject user = new BasicDBObject();
		user.put("id", id);
		rest = getRest();
		rest.remove(user);
		
	}

	@Override
	public String doGet() {
		System.out.println("RESTSampleDAOImpl    !");
		return null;
	}

	@Override
	public String doRequest(String param) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public User getBean(int id) {
		rest = getRest();
		User user = new User();
		List<DBObject> dbObjects = rest.find(new BasicDBObject("id",id)).toArray();
		if(dbObjects != null && dbObjects.size()>0){
			DBObject obj1 = dbObjects.get(0);
			user = MongoUtil.dbObject2Bean(obj1, user);
		}
//		user = MongoUtil.dbObject2Bean(obj1, user);
		
		return user;
	}

	@Override
	public List<User> getList(){
		 rest = getRest();
		 DBCursor cursor = rest.find();
		 List<DBObject> list = cursor.toArray();
		 List<User> users = new ArrayList<User>();
		 for (DBObject obj : list) {
			 User user = new User();
			 user = MongoUtil.dbObject2Bean(obj, user);
			 users.add(user);
		}
		return users;
	}

	@Override
	public MapBean getMap() {
		
		return null;
	}

	@Override
	public User postData(User user) throws IOException {
		DBObject obj = null;
		try {
			obj = MongoUtil.bean2DBObject(user);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		rest = getRest();
		rest.save(obj);
		return user;
	}

	@Override
	public User putData(int id, User user) {
		rest = getRest();
		DBObject obj = null;
		try {
			obj = MongoUtil.bean2DBObject(user);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		rest.update(new BasicDBObject().append("id", id), obj);
		return user;
	}

	public DBCollection getRest() {
		rest = super.getCollection("rest");
		return rest;
	}


}
